<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>预约管理 - 智慧小区管理系统</title>
    <link rel="stylesheet" href="../lib/layui-v2.6.3/css/layui.css">
    <script src="../lib/jquery-3.4.1/jquery-3.4.1.min.js"></script>
    <style>
        body { padding: 24px; background: #f5f7fa; }
        .appointment-toolbar { margin-bottom: 16px; }
        .layui-table th, .layui-table td { text-align: center; }
        .status-badge { padding: 4px 8px; border-radius: 4px; font-size: 12px; color: white; }
        .status-pending { background-color: #FFB800; }
        .status-completed { background-color: #5FB878; }
        .status-cancelled { background-color: #FF5722; }
    </style>
</head>
<body>
<div class="layui-card">
    <div class="layui-card-header" style="font-size:1.2em;font-weight:bold;">预约管理</div>
    <div class="layui-card-body">
        <!-- 搜索表单 -->
        <form class="layui-form appointment-toolbar" id="searchForm">
            <div class="layui-inline">
                <label class="layui-form-label" style="width: 80px;">服务类型</label>
                <div class="layui-input-inline" style="width: 120px;">
                    <select name="serviceType" id="serviceTypeSelect">
                        <option value="">全部类型</option>
                    </select>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label" style="width: 80px;">状态</label>
                <div class="layui-input-inline" style="width: 120px;">
                    <select name="status" id="statusSelect">
                        <option value="">全部状态</option>
                        <option value="1">待确认</option>
                        <option value="2">已完成</option>
                        <option value="3">已取消</option>
                    </select>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label" style="width: 80px;">预约日期</label>
                <div class="layui-input-inline" style="width: 150px;">
                    <input type="text" name="appointmentDate" id="appointmentDate" placeholder="选择日期" class="layui-input">
                </div>
            </div>
            <button class="layui-btn layui-btn-normal" lay-submit lay-filter="search">
                <i class="layui-icon layui-icon-search"></i> 查询
            </button>
            <button class="layui-btn layui-btn-primary" type="reset">
                <i class="layui-icon layui-icon-refresh"></i> 重置
            </button>
        </form>
        <!-- 工具栏 -->
        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-primary layui-btn-sm" onclick="refreshTable()">
                    <i class="layui-icon layui-icon-refresh"></i> 刷新
                </button>
            </div>
        </script>
        <!-- 操作栏模板 -->
        <script type="text/html" id="tableBar">
            {{# if(d.status == 1) { }}
            <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="cancel" title="取消预约">
                <i class="layui-icon layui-icon-close"></i> 取消预约
            </a>
            <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="finish" title="完成预约">
                <i class="layui-icon layui-icon-ok"></i> 完成预约
            </a>
            {{# } else { }}
            <a class="layui-btn layui-btn-disabled layui-btn-xs" style="pointer-events:none;opacity:0.6;" title="仅待确认可取消">
                <i class="layui-icon layui-icon-close"></i> 取消预约
            </a>
            <a class="layui-btn layui-btn-disabled layui-btn-xs" style="pointer-events:none;opacity:0.6;" title="仅待确认可完成">
                <i class="layui-icon layui-icon-ok"></i> 完成预约
            </a>
            {{# } }}
            {{# if(d.status == 2 || d.status == 3) { }}
            <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete" title="删除">
                <i class="layui-icon layui-icon-delete"></i> 删除
            </a>
            {{# } else { }}
            <a class="layui-btn layui-btn-disabled layui-btn-xs" style="pointer-events:none;opacity:0.6;" title="仅已完成或已取消可删除">
                <i class="layui-icon layui-icon-delete"></i> 删除
            </a>
            {{# } }}
        </script>
        
        <!-- 状态模板 -->
        <script type="text/html" id="statusTpl">
            {{# if(d.status == 1) { }}
                <span class="status-badge status-pending">待确认</span>
            {{# } else if(d.status == 2) { }}
                <span class="status-badge status-completed">已完成</span>
            {{# } else if(d.status == 3) { }}
                <span class="status-badge status-cancelled">已取消</span>
            {{# } else { }}
                <span>未知状态</span>
            {{# } }}
        </script>
        <!-- 数据表格 -->
        <table class="layui-table" id="appointmentTable" lay-filter="appointmentTableFilter"></table>
    </div>
</div>
<script src="../lib/layui-v2.6.3/layui.js"></script>
<script>
layui.use(['table', 'form', 'layer', 'jquery', 'laydate'], function () {
    const table = layui.table;
    const form = layui.form;
    const layer = layui.layer;
    const $ = layui.jquery;
    const laydate = layui.laydate;
    let serviceTypeMap = {};
    // 日期选择器
    laydate.render({
        elem: '#appointmentDate',
        type: 'date',
        min: 0
    });
    $.ajaxSetup({
        beforeSend: function(xhr) {
            const data = JSON.parse(localStorage.getItem('user'));
            if (data && data.token) {
                xhr.setRequestHeader('Authorization', 'Bearer ' + data.token);
            }
        }
    });
    // 动态加载服务类型
    function loadServiceTypes() {
        $.get('/medical/services', function(res) {
            var $select = $('#serviceTypeSelect');
            $select.empty();
            $select.append('<option value="">全部类型</option>');
            if (res.code === 0 && Array.isArray(res.data)) {
                res.data.forEach(function(item) {
                    $select.append('<option value="'+item.serviceType+'">'+item.serviceName+'</option>');
                    serviceTypeMap[item.serviceType] = item.serviceName;
                });
            }
            form.render('select');
        });
    }
    function loadStatusOptions() {
        var $select = $('#statusSelect');
        $select.empty();
        $select.append('<option value="">全部状态</option>');
        $select.append('<option value="1">待确认</option>');
        $select.append('<option value="2">已完成</option>');
        $select.append('<option value="3">已取消</option>');
        form.render('select');
    }
    // 表格初始化
    function renderAppointmentTable(whereData) {
        table.render({
            elem: '#appointmentTable',
            id: 'appointmentTable',
            url: '/medical/appointment/list',
            method: 'get',
            where: whereData || {},
            toolbar: '#toolbarDemo',
            page: true,
            limit: 10,
            limits: [10, 15, 20, 50],
            height: 'full-200',
            cols: [[
                { field: 'appointmentId', title: '预约ID', minWidth: 80, align: 'center' },
                { field: 'residentId', title: '居民ID', minWidth: 80, align: 'center' },
                { field: 'serviceType', title: '服务类型', minWidth: 120, align: 'center', templet: function(d) {
                    return serviceTypeMap[d.serviceType] || '<span style="color:#bbb;">未知类型</span>';
                } },
                { field: 'doctorName', title: '指定医生', minWidth: 100, align: 'center' },
                { field: 'phone', title: '联系电话', minWidth: 120, align: 'center' },
                { field: 'appointmentDate', title: '预约日期', minWidth: 120, align: 'center' },
                { field: 'timeSlot', title: '时间段', minWidth: 120, align: 'center' },
                { field: 'location', title: '地点', minWidth: 120, align: 'center' },
                { field: 'duration', title: '时长(分钟)', minWidth: 80, align: 'center' },
                { field: 'price', title: '价格', minWidth: 80, align: 'center', templet: function(d){ return d.price ? '¥'+parseFloat(d.price).toFixed(2) : ''; } },
                { field: 'status', title: '状态', minWidth: 100, templet: '#statusTpl', align: 'center' },
                { field: 'remark', title: '备注', minWidth: 120, align: 'center' },
                { title: '操作', toolbar: '#tableBar', width: 280, align: 'center', fixed: 'right' }
            ]],
            parseData: function(res) {
                return {
                    code: res.code === 0 ? 0 : 1,
                    msg: res.message || '',
                    count: res.count || 0,
                    data: res.data || []
                };
            }
        });
    }
    // 初始化
    loadServiceTypes();
    loadStatusOptions();
    renderAppointmentTable({}); // 初始化时传空对象
    // 查询表单提交
    form.on('submit(search)', function (data) {
        var whereData = Object.assign({}, data.field);
        if(whereData.appointmentDate) {
            whereData.appointmentDate = whereData.appointmentDate.replace(/\//g, '-');
        }
        table.reload('appointmentTable', {
            where: whereData,
            page: { curr: 1 }
        });
        return false;
    });
    // 重置按钮
    $(document).on('click', '.layui-btn-primary[type="reset"]', function () {
        $('#searchForm')[0].reset();
        form.render();
        table.reload('appointmentTable', {
            where: {},
            page: { curr: 1 }
        });
        return false;
    });
    // 刷新表格
    window.refreshTable = function() {
        table.reload('appointmentTable', {
            where: {},
            page: { curr: 1 }
        });
        layer.msg('数据已刷新', {icon: 1});
    };
    // 监听行工具事件
    table.on('tool(appointmentTableFilter)', function(obj){
        const data = obj.data;
        if(obj.event === 'cancel') {
            if(data.status !== 1) {
                layer.msg('只有待确认的预约才能取消', {icon: 0});
                return;
            }
            layer.confirm('确定要取消这个预约吗？', function(index){
                $.ajax({
                    url: '/medical/appointment/cancel',
                    type: 'POST',
                    data: { appointmentId: data.appointmentId },
                    success: function(res) {
                        if(res.code === 0) {
                            layer.msg('预约已取消', {icon: 1});
                            table.reload('appointmentTable');
                        } else {
                            layer.msg(res.message || '取消失败', {icon: 2});
                        }
                    },
                    error: function() {
                        layer.msg('网络错误，取消失败', {icon: 2});
                    },
                    complete: function() {
                        layer.close(index);
                    }
                });
            });
        } else if(obj.event === 'finish') {
            if(data.status !== 1) {
                layer.msg('只有待确认的预约才能完成', {icon: 0});
                return;
            }
            layer.confirm('确定要将该预约标记为已完成吗？', function(index){
                $.ajax({
                    url: '/medical/appointment/finish',
                    type: 'POST',
                    data: { appointmentId: data.appointmentId },
                    success: function(res) {
                        if(res.code === 0) {
                            layer.msg('已标记为完成', {icon: 1});
                            table.reload('appointmentTable');
                        } else {
                            layer.msg(res.message || '操作失败', {icon: 2});
                        }
                    },
                    error: function() {
                        layer.msg('网络错误，操作失败', {icon: 2});
                    },
                    complete: function() {
                        layer.close(index);
                    }
                });
            });
        } else if(obj.event === 'delete') {
            if(data.status !== 2 && data.status !== 3) {
                layer.msg('只有已完成或已取消的预约才能删除', {icon: 0});
                return;
            }
            layer.confirm('确定删除该预约记录吗？', function(index){
                $.ajax({
                    url: '/medical/appointment/delete',
                    type: 'POST',
                    data: { appointmentId: data.appointmentId },
                    success: function(res) {
                        if(res.code === 0) {
                            layer.msg('删除成功', {icon: 1});
                            table.reload('appointmentTable');
                        } else {
                            layer.msg(res.message || '删除失败', {icon: 2});
                        }
                    },
                    error: function() {
                        layer.msg('网络错误，删除失败', {icon: 2});
                    },
                    complete: function() {
                        layer.close(index);
                    }
                });
            });
        }
    });
});
</script>
</body>
</html> 